package com.example.blog.controller;

import com.example.blog.entity.Category;
import com.example.blog.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/categories")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public ResponseEntity<?> createCategory(@RequestBody Map<String, String> categoryRequest) {
        try {
            String name = categoryRequest.get("name");
            String description = categoryRequest.get("description");
            Category category = categoryService.createCategory(name, description);
            return ResponseEntity.status(HttpStatus.CREATED).body(category);
        } catch (RuntimeException e) {
            Map<String, Object> errorMap = new HashMap<>();
errorMap.put("error", e.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorMap);
        }
    }

    @GetMapping
    public ResponseEntity<List<Category>> getAllCategories() {
        List<Category> categories = categoryService.findAll();
        return ResponseEntity.ok(categories);
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> getCategoryById(@PathVariable Long id) {
        try {
            Category category = categoryService.findById(id);
            return ResponseEntity.ok(category);
        } catch (RuntimeException e) {
            Map<String, Object> errorMap = new HashMap<>();
errorMap.put("error", e.getMessage());
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorMap);
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<?> updateCategory(@PathVariable Long id, @RequestBody Map<String, String> categoryRequest) {
        try {
            String name = categoryRequest.get("name");
            String description = categoryRequest.get("description");
            Category category = categoryService.updateCategory(id, name, description);
            return ResponseEntity.ok(category);
        } catch (RuntimeException e) {
            Map<String, Object> errorMap = new HashMap<>();
errorMap.put("error", e.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorMap);
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteCategory(@PathVariable Long id) {
        try {
            categoryService.deleteCategory(id);
            Map<String, Object> successMap = new HashMap<>();
successMap.put("message", "分类删除成功");
return ResponseEntity.ok(successMap);
        } catch (RuntimeException e) {
            Map<String, Object> errorMap = new HashMap<>();
errorMap.put("error", e.getMessage());
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorMap);
        }
    }

}